package com.panda.web.service.commons.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.panda.web.domain.vo.EditionVO;
import com.panda.web.entity.commons.SpecialEdition;
import com.panda.web.mapper.commons.SpecialEditionMapper;
import com.panda.web.service.commons.ISpecialEditionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.text.Collator;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 专业分类Service业务层处理
 *
 * @author cpanda
 * @date 2025-03-05
 */
@Slf4j
@Service
public class SpecialEditionServiceImpl extends ServiceImpl<SpecialEditionMapper, SpecialEdition> implements ISpecialEditionService {
    @Autowired
    SpecialEditionMapper editionMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<SpecialEdition> PageList(SpecialEdition dto, Integer pageNum, Integer pageSize) {

        Page<SpecialEdition> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SpecialEdition> queryWrapper = new QueryWrapper();//需要处理查询条件
        IPage<SpecialEdition> editionIPage = editionMapper.selectPage(page, queryWrapper);
        long total = editionIPage.getTotal();
        List<SpecialEdition> records = editionIPage.getRecords();

        return new PageResult<>(records, total, pageNum, pageSize);
    }

    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<SpecialEdition> choiceList(SpecialEdition dto) {
        QueryWrapper<SpecialEdition> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        List<SpecialEdition> editionList = editionMapper.selectList(queryWrapper);

        return editionList;
    }

    /**
     * 回显数据
     *
     * @param editionId
     * @return
     */
    @Override
    public SpecialEdition selectById(Long editionId) {
        SpecialEdition edition = editionMapper.selectById(editionId);
        return edition;
    }

    /**
     * 新增
     *
     * @param edition
     * @return
     */
    @Override
    public int insert(SpecialEdition edition) {
        editionMapper.insert(edition);
        return 1;
    }

    /**
     * 修改数据
     *
     * @param edition
     * @return
     */
    @Override
    public int updateEditionById(SpecialEdition edition) {

        editionMapper.updateById(edition);
        return 1;
    }

    /**
     * 删除数据(逻辑删除)
     *
     * @param ids
     * @return
     */
    @Override
    public int removeByEditionIds(List<Long> ids) {
        for (Long id : ids) {
            SpecialEdition edition = editionMapper.selectById(id);
            editionMapper.updateById(edition);
        }
        return 1;
    }

    /**
     * 树结构查询
     *
     * @param edition
     * @return
     */
    @Override
    public List<EditionVO> getSpecialTree(SpecialEdition edition) {
        // 1. 查询所有数据
        List<SpecialEdition> allEditions = editionMapper.selectList(null);

        // 2. 构建树形结构
        List<EditionVO> rootNodes = allEditions.stream()
                .filter(e -> e.getParentId() == 0) // 一级节点
                .map(this::convertToVO)
                .sorted((a, b) -> Collator.getInstance(Locale.CHINA).compare(a.getName(), b.getName()))
                .collect(Collectors.toList());

        // 3. 递归构建树形结构
        for (EditionVO rootNode : rootNodes) {
            buildTree(rootNode, allEditions);
        }

        // 4. 根据名称进行模糊搜索
        if (edition.getName() != null && !edition.getName().isEmpty()) {
            rootNodes = filterTreeByName(rootNodes, edition.getName());
        }

        return rootNodes;
    }

    private EditionVO convertToVO(SpecialEdition edition) {
        EditionVO vo = new EditionVO();
        vo.setSpecialId(edition.getSpecialId());
        vo.setParentId(edition.getParentId());
        vo.setName(edition.getName());
        vo.setClassName(edition.getClassName());
        return vo;
    }

    //子节点
    private void buildTree(EditionVO parentNode, List<SpecialEdition> allEditions) {
        List<EditionVO> children = allEditions.stream()
                .filter(e -> e.getParentId().equals(parentNode.getSpecialId()))
                .map(this::convertToVO)
                .sorted((a, b) -> Collator.getInstance(Locale.CHINA).compare(a.getName(), b.getName()))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            parentNode.setChildren(children);
            for (EditionVO child : children) {
                buildTree(child, allEditions);
            }
        }
    }

    private List<EditionVO> filterTreeByName(List<EditionVO> nodes, String name) {
        List<EditionVO> result = new ArrayList<>();
        if (nodes == null) {
            return result; // 如果 nodes 为 null，直接返回空列表
        }

        for (EditionVO node : nodes) {
            // 检查当前节点是否匹配
            boolean isCurrentNodeMatch = node.getName() != null && node.getName().contains(name);

            // 递归检查子节点
            List<EditionVO> filteredChildren = null;
            if (node.getChildren() != null) {
                filteredChildren = filterTreeByName(node.getChildren(), name);
            }

            // 如果当前节点匹配，或者子节点有匹配，则加入结果
            if (isCurrentNodeMatch || (filteredChildren != null && !filteredChildren.isEmpty())) {
                EditionVO copyNode = new EditionVO();
                copyNode.setSpecialId(node.getSpecialId());
                copyNode.setParentId(node.getParentId());
                copyNode.setName(node.getName());
                copyNode.setClassName(node.getClassName());

                // 如果当前节点匹配，返回所有子节点
                if (isCurrentNodeMatch) {
                    copyNode.setChildren(node.getChildren()); // 返回所有子节点
                } else if (filteredChildren != null && !filteredChildren.isEmpty()) {
                    // 如果子节点有匹配，设置过滤后的子节点
                    copyNode.setChildren(filteredChildren);
                }

                result.add(copyNode);
            }
        }
        return result;
    }


//    // 处理VO数据封装
//    private List<EditionVO> editionVoToList(List<SpecialEdition> editionList) {
//        List<EditionVO> voList = new ArrayList<>();
//        if (editionList.size() > 0 && !editionList.isEmpty()) {
//            for (SpecialEdition edition :editionList){
//                EditionVO vo = new EditionVO();
//                BeanUtils.copyProperties(edition, vo);
//                voList.add(vo);
//            }
//        }
//        return voList;
//    }


}